package com.zjl.aop;

import com.alibaba.fastjson.JSONObject;

import com.zjl.mapper.OperateLogMapper;
import com.zjl.pojo.OperateLog;
import com.zjl.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @ClassName LogAspect
 * @Author ZJL
 * @Date 2023/11/3 12:15
 * @Version 1.0
 **/
@Slf4j
@Component
@Aspect //切面类
public class LogAspect {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.zjl.anno.Log)")
    public Object recordLog(ProceedingJoinPoint point) throws Throwable {
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        //开始时间
        long begin = System.currentTimeMillis();
        //操作人Id
        Integer operateUser = (Integer) claims.get("id");
        //操作时间
        LocalDateTime operateTime = LocalDateTime.now();
        //操作类名
        String className = point.getTarget().getClass().getName();
        //操作方法名
        String methodName = point.getSignature().getName();
        //操作方法参数
        Object[] args = point.getArgs();
        String methodParams = Arrays.toString(args);

        //调用原始目标方法运行
        Object result = point.proceed();
        //方法返回值
        String returnValue = JSONObject.toJSONString(result);
        //结束时间
        long end = System.currentTimeMillis();
        //操作耗时
        Long costTime = end - begin;
        //记录操作日志
        OperateLog operateLog = new OperateLog(null,operateUser,operateTime,className,methodName,methodParams,returnValue,costTime);
        operateLogMapper.insert(operateLog);

        log.info("AOP记录操作日志: {}" , operateLog);

        return result;
    }

}
